package com.yunxin.core.wechat.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.common.utils.OkHttpUtils;
import com.yunxin.core.utils.infra.utils.BeanCopierUtils;
import com.yunxin.core.wechat.config.WechatConstants;
import com.yunxin.core.wechat.domain.*;
import com.yunxin.core.wechat.dto.GetWechatCustomersDto;
import com.yunxin.core.wechat.dto.UpdateWechatCustomerRemarkDto;
import com.yunxin.core.wechat.dto.UpdateWechatCustomerTagsDto;
import com.yunxin.core.wechat.javaxml.com.qq.weixin.mp.aes.AesException;
import com.yunxin.core.wechat.javaxml.com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.yunxin.core.wechat.service.*;
import com.yunxin.core.wechat.utils.ConstantUtil;
import com.yunxin.core.wechat.vo.LoginDetailVo;
import com.yunxin.core.wechat.vo.LoginVo;
import com.yunxin.core.wechat.vo.WechatFollowCustomerListVo;
import com.yunxin.core.wechat.vo.WechatGroupTagVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class QyWxServiceImpl implements QyWxService {

    @Value("${qiyewx.url}")
    private String wechatUrl;

//    @Autowired
//    private QyWxConfig qyWxConfig;

    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private WechatInfoService wechatInfoService;
    @Autowired
    private WechatAuthService wechatAuthService;
    @Autowired
    private WechatTagInfoService wechatTagInfoService;
    @Autowired
    @Lazy
    private WechatFollowCustomerService wechatFollowCustomerService;
    @Autowired
    private WechatUserSysService wechatUserSysService;

    /**
     * 验证回调URL
     *
     * @param request
     * @param type  1微信验证
     * @return
     */
    @Override
    public Object verificationUrl(HttpServletRequest request,Integer type, WechatInfo wechatInfo) throws AesException {
        log.info("=========验证URL有效性开始=========");
        String sEchoStr; //需要返回的明文
        try {
            WXBizMsgCrypt wxcpt =null;
            if (!ObjectUtils.isEmpty(type)&&type==1){
                wxcpt = new WXBizMsgCrypt(wechatInfo.getMessageToken(), wechatInfo.getMessageEncodingAesKey(), wechatInfo.getCorpid());
            }else {
                wxcpt = new WXBizMsgCrypt(wechatInfo.getToken(), wechatInfo.getEncodingAesKey(), wechatInfo.getCorpid());
            }
            String msgSignature = request.getParameter("msg_signature");
            String timeStamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("企业微信加密签名: {},时间戳: {},随机数: {},加密的字符串: {}", msgSignature, timeStamp, nonce, echostr);
            sEchoStr = wxcpt.VerifyURL(msgSignature,
                    timeStamp,
                    nonce,
                    echostr);
            log.info("给企业微信返回的明文,{}", sEchoStr);
            log.info("=========验证URL有效性结束=========");
            return sEchoStr;

        } catch (AesException e) {
            log.error("验证URL失败，错误原因请查看异常:{}", e.getCode());
            throw new AesException(e.getCode());
        }
    }

    @Override
    public Map<String, String> getRequestParameter(HttpServletRequest request, String body, WechatInfo wechatInfo) throws AesException {
        log.info("=========参数解析开始=========");
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(wechatInfo.getToken(), wechatInfo.getEncodingAesKey(), wechatInfo.getCorpid());
            String msgSignature = request.getParameter("msg_signature");
            String timeStamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            log.info("企业微信加密签名: {},时间戳: {},随机数: {}", msgSignature, timeStamp, nonce);
            String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, body);
            Map<String, String> resultMap = new HashMap<String, String>(16);
            resultMap = ConstantUtil.parseXmlToMap(sMsg, resultMap);
            log.info("decrypt密文转为map结果为{}", resultMap);
            log.info("=========参数解析结束=========");
            //将suite_ticket存如redis
            String event = resultMap.get("Event");
            if (!ObjectUtils.isEmpty(event)) {
                //客户事件
                if (event.equals("change_external_contact")) {
                    contactEvent(resultMap);
                    System.out.println("用户客户事件: " + JSON.toJSONString(resultMap));
                }
                //客户群事件
                if (event.equals("change_external_chat")) {
                    chatEvent(resultMap);
                    System.out.println("用户客户群事件: " + JSON.toJSONString(request));
                }
                //客户标签事件
                if (event.equals("change_external_tag")) {
                    tagEvent(resultMap);
                    System.out.println("用户标签事件: " + JSON.toJSONString(request));
                }
            }
            return resultMap;
        } catch (AesException e) {
            log.error("密文参数解析失败，错误原因请查看异常:{}", e.getMessage());
            throw new AesException(e.getCode());
        }
    }

    private void contactEvent(Map<String, String> resultMap) {
        LambdaQueryWrapper<WechatUserSys> wechatUserSysLambdaQueryWrapper = new LambdaQueryWrapper<>();
        wechatUserSysLambdaQueryWrapper.eq(WechatUserSys::getWechatUserId, resultMap.get("UserID"))
                .eq(WechatUserSys::getCorpid, resultMap.get("ToUserName"));
        WechatUserSys wechatUserSys = wechatUserSysService.getOne(wechatUserSysLambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(wechatUserSys)) {
            //添加企业客户事件 add_external_contact (成为客户回调事件)
            if (resultMap.get("ChangeType").equals("add_external_contact")) {
                //获得客户信息
                WechatFollowCustomer wechatCustomer = getWechatCustomer(resultMap.get("ToUserName"), resultMap.get("ExternalUserID"), resultMap.get("UserID"));
                if (!ObjectUtils.isEmpty(wechatCustomer)) {
                    //保存或刷新客户信息
                    wechatCustomer.setRunType(0);
                    wechatCustomer.setSysUserId(wechatUserSys.getSysUserId());
                    wechatCustomer.setWechatInfoId(wechatUserSys.getWechatInfoId());
                    wechatFollowCustomerService.refWectCoustomer(wechatCustomer,wechatUserSys);
                }
            }
            //编辑企业客户事件 edit_external_contact
            if (resultMap.get("ChangeType").equals("edit_external_contact")) {
                //获得客户信息
                WechatFollowCustomer wechatCustomer = getWechatCustomer(resultMap.get("ToUserName"), resultMap.get("ExternalUserID"), resultMap.get("UserID"));
                if (!ObjectUtils.isEmpty(wechatCustomer)) {
                    //保存或刷新客户信息
                    wechatCustomer.setSysUserId(wechatUserSys.getSysUserId());
                    wechatCustomer.setWechatInfoId(wechatUserSys.getWechatInfoId());
                    wechatFollowCustomerService.refWectCoustomer(wechatCustomer,wechatUserSys);
                }
            }
            //外部联系人免验证添加成员事件 add_half_external_contact
            if (resultMap.get("ChangeType").equals("add_half_external_contact")) {
                //获得客户信息
                WechatFollowCustomer wechatCustomer = getWechatCustomer(resultMap.get("ToUserName"), resultMap.get("ExternalUserID"), resultMap.get("UserID"));
                if (!ObjectUtils.isEmpty(wechatCustomer)) {
                    //保存或刷新客户信息
                    wechatCustomer.setSysUserId(wechatUserSys.getSysUserId());
                    wechatCustomer.setWechatInfoId(wechatUserSys.getWechatInfoId());
                    wechatFollowCustomerService.refWectCoustomer(wechatCustomer,wechatUserSys);
                }
            }
            //删除企业客户事件 del_external_contact
            if (resultMap.get("ChangeType").equals("del_external_contact")) {
                wechatFollowCustomerService.refRunCoustomer(wechatUserSys,resultMap.get("ExternalUserID"),1,Long.parseLong(resultMap.get("CreateTime")),resultMap.get("Source"));
            }
            //删除跟进成员事件 del_follow_user  被外部联系人删除
            if (resultMap.get("ChangeType").equals("del_follow_user")) {
                wechatFollowCustomerService.refRunCoustomer(wechatUserSys,resultMap.get("ExternalUserID"),2,Long.parseLong(resultMap.get("CreateTime")),resultMap.get("Source"));
            }
            //客户接替失败事件 transfer_fail
            if (resultMap.get("ChangeType").equals("transfer_fail")) {

            }
        }
    }

    private void chatEvent(Map<String, String> resultMap) {
        //客户群创建事件 create
        if (resultMap.get("ChangeType").equals("create")) {

        }
        //客户群变更事件 update
        if (resultMap.get("ChangeType").equals("update")) {

        }
        //客户群解散事件 dismiss
        if (resultMap.get("ChangeType").equals("dismiss")) {

        }
    }

    private void tagEvent(Map<String, String> resultMap) {
        LambdaQueryWrapper<WechatInfo> wechatInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        wechatInfoLambdaQueryWrapper.eq(WechatInfo::getCorpid, resultMap.get("ToUserName"));
        WechatInfo wechatInfo = wechatInfoService.getOne(wechatInfoLambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(wechatInfo)){
            //企业客户标签创建事件 create
            if (resultMap.get("ChangeType").equals("create")) {
                this.getAllTags(wechatInfo.getId(),wechatInfo.getCorpid());
            }
            //企业客户标签变更事件 update
            if (resultMap.get("ChangeType").equals("update")) {
                this.getAllTags(wechatInfo.getId(),wechatInfo.getCorpid());
            }
            //企业客户标签删除事件 delete
            if (resultMap.get("ChangeType").equals("delete")) {
                LambdaQueryWrapper<WechatTagInfo> wechatTagInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
                wechatTagInfoLambdaQueryWrapper.eq(WechatTagInfo::getWechatInfoId,wechatInfo.getId())
                        .eq(WechatTagInfo::getTagId,resultMap.get("Id"));
                WechatTagInfo wechatTagInfo = wechatTagInfoService.getOne(wechatTagInfoLambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(wechatTagInfo)){
                    if (resultMap.get("TagType").equals("tag_group")){
                        wechatTagInfoLambdaQueryWrapper.clear();
                        wechatTagInfoLambdaQueryWrapper.eq(WechatTagInfo::getWechatGroupId,wechatTagInfo.getTagId())
                                .eq(WechatTagInfo::getWechatInfoId,wechatInfo.getId());
                        wechatTagInfoService.remove(wechatTagInfoLambdaQueryWrapper);
                    }
                    wechatTagInfoService.removeById(wechatTagInfo);
                }
            }
        }
    }

    @Override
    public String getCorpTokenByCorpId(String corpId) {
        Object corpTokenObject = redisTemplate.opsForValue().get(WechatConstants.ACCESS_TOKEN + corpId);
        if (!ObjectUtils.isEmpty(corpTokenObject)) {
            return corpTokenObject.toString();
        }
        LambdaQueryWrapper<WechatInfo> wechatInfoWrapper = new LambdaQueryWrapper<>();
        wechatInfoWrapper.eq(WechatInfo::getCorpid, corpId);
        WechatInfo wechatInfo = wechatInfoService.getOne(wechatInfoWrapper);
        if (ObjectUtils.isEmpty(wechatInfo)) {
            return null;
        }
        String post = OkHttpUtils.X.get(wechatUrl + "/cgi-bin/gettoken?" + "corpid="+wechatInfo.getCorpid()+"&corpsecret="+wechatInfo.getSecret());
        JSONObject parse = JSON.parseObject(post);
        String corpToken = parse.getString("access_token");
        redisTemplate.opsForValue().set(WechatConstants.ACCESS_TOKEN + wechatInfo.getCorpid(), parse.getString("access_token"), 7190L, TimeUnit.SECONDS);
        return corpToken;
    }

    @Override
    public LoginVo getuserinfo(String code, WechatInfo wechatInfo) {
        String post = OkHttpUtils.X.get(wechatUrl + "/cgi-bin/auth/getuserinfo?access_token=" + this.getCorpTokenByCorpId(wechatInfo.getCorpid()) + "&code=" + code);
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            if (ObjectUtils.isEmpty(jsonObject.getString("userid"))) {
                return null;
            }
            LoginVo loginVo = new LoginVo();
            loginVo.setCorpid(wechatInfo.getCorpid());
            loginVo.setUserid(jsonObject.getString("userid"));
            //LoginDetailVo userTicket = this.getuserdetail(wechatInfo.getCorpid(), jsonObject.getString("user_ticket"));
            return loginVo;
        }
        return null;
    }

    @Override
    public String getWechatUserByPhone(String phone, String corpId) {
        //通过手机号获取指定成员id  OK
        Map<String, Object> map = new HashMap();
        map.put("mobile", phone);
        String idPost = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/user/getuserid?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(map));
        //System.out.println(idPost);
        JSONObject jsonObject = JSON.parseObject(idPost);
        //通过用户id 读取成员 OK
        if (jsonObject.getString("errmsg").equals("ok")) {
            return jsonObject.getString("userid");
        }
        return null;
    }

    @Override
    public String getWechatUserByEmail(String email, String corpId, Integer emailType) {
        //通过手机号获取指定成员id  OK
        Map<String, Object> map = new HashMap();
        map.put("email", email);
        map.put("email_type", emailType);
        String idPost = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/user/get_userid_by_email?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(map));
        //System.out.println(idPost);
        JSONObject jsonObject = JSON.parseObject(idPost);
        //通过用户id 读取成员 OK
        if (jsonObject.getString("errmsg").equals("ok")) {
            return jsonObject.getString("userid");
        }
        return null;
    }

    @Override
    public List<WechatGroupTagVo> getWechatTags(String corpId) {
        Map<String, Object> map = new HashMap();
        //map.put("group_id",null);
        //map.put("tag_id",null);
        String postbiaoqian = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/externalcontact/get_corp_tag_list?access_token=" + this.getCorpTokenByCorpId(corpId),JacksonUtils.X.format(map));
        JSONObject jsonObject = JSON.parseObject(postbiaoqian);
        // System.out.println(postbiaoqian);
        if (jsonObject.getString("errmsg").equals("ok")) {
            JSONArray tagGroups = jsonObject.getJSONArray("tag_group");
            List<WechatGroupTagVo> wechatGroupTagVoList = new ArrayList<>();
            for (Object tagGroup : tagGroups) {
                JSONObject tagGroupJson = (JSONObject) tagGroup;
                WechatGroupTagVo wechatGroupTagVo = new WechatGroupTagVo();
                wechatGroupTagVo.setGroup_id(tagGroupJson.getString("group_id"));
                wechatGroupTagVo.setGroup_name(tagGroupJson.getString("group_name"));
                wechatGroupTagVo.setCreate_time(tagGroupJson.getLong("create_time"));
                JSONArray tags = tagGroupJson.getJSONArray("tag");
                List<WechatGroupTagVo.WechatTagVo> wechatTagVoList = new ArrayList<>();
                for (Object tag : tags) {
                    JSONObject tagJson = (JSONObject) tag;
                    WechatGroupTagVo.WechatTagVo wechatTagVo = new WechatGroupTagVo.WechatTagVo();
                    wechatTagVo.setId(tagJson.getString("id"));
                    wechatTagVo.setName(tagJson.getString("name"));
                    wechatTagVo.setCreate_time(tagJson.getLong("create_time"));
                    wechatTagVo.setOrder(tagJson.getInteger("order"));
                    wechatTagVoList.add(wechatTagVo);
                }
                wechatGroupTagVo.setTags(wechatTagVoList);
                wechatGroupTagVoList.add(wechatGroupTagVo);
            }
            return wechatGroupTagVoList;
        }
        return null;
    }

    @Override
    public WechatFollowCustomerListVo getWechatCustomers(String corpId, GetWechatCustomersDto getWechatCustomersDto) {
        Map<String, Object> stringObjectMap = BeanCopierUtils.X.convertClassToMap(getWechatCustomersDto);
        String post = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/externalcontact/batch/get_by_user?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(stringObjectMap));
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            JSONArray externalContactList = jsonObject.getJSONArray("external_contact_list");
            WechatFollowCustomerListVo wechatFollowCustomerListVo = new WechatFollowCustomerListVo();
            wechatFollowCustomerListVo.setNext_cursor(jsonObject.getString("next_cursor"));
            for (Object externalJson : externalContactList) {
                JSONObject wechatCustomerJson = (JSONObject) externalJson;
                WechatFollowCustomer wechatFollowCustomer = new WechatFollowCustomer();
                JSONObject followInfo = wechatCustomerJson.getJSONObject("follow_info");
                wechatFollowCustomer.setWechatUserId(followInfo.getString("userid"));
                wechatFollowCustomer.setRemark(followInfo.getString("remark"));
                wechatFollowCustomer.setDescription(followInfo.getString("description"));
                wechatFollowCustomer.setWechatRemarkMobiles(followInfo.getString("remark_mobiles"));

                wechatFollowCustomer.setWechatCreatetime(followInfo.getLong("createtime"));
                wechatFollowCustomer.setWechatTagIds(ObjectUtils.isEmpty(followInfo.getJSONArray("tag_id")) ? null : JSON.toJSONString(followInfo.getJSONArray("tag_id")));
                wechatFollowCustomer.setRemarkCorpName(followInfo.getString("remark_corp_name"));
                wechatFollowCustomer.setAddWay(followInfo.getInteger("add_way"));
                wechatFollowCustomer.setOperUserid(followInfo.getString("oper_userid"));
                //wechatFollowCustomer.setCustomerNo(followInfo.getString("remark_corp_name"));

                JSONObject externalContact = wechatCustomerJson.getJSONObject("external_contact");
                wechatFollowCustomer.setExternalUserid(externalContact.getString("external_userid"));
                wechatFollowCustomer.setWechatName(externalContact.getString("name"));
                wechatFollowCustomer.setWechatType(externalContact.getInteger("type"));
                wechatFollowCustomer.setWechatAuatar(externalContact.getString("avatar"));
                wechatFollowCustomer.setWechatGender(externalContact.getInteger("gender"));
                wechatFollowCustomer.setWechatUnionid(externalContact.getString("unionid"));
                wechatFollowCustomerListVo.getWechatFollowCustomerList().add(wechatFollowCustomer);
            }
            return wechatFollowCustomerListVo;
        }
        return null;
    }

    @Override
    public WechatFollowCustomer getWechatCustomer(String corpId, String externalUserid, String wechatUserid) {
        String post = OkHttpUtils.X.get(wechatUrl + "/cgi-bin/externalcontact/get?access_token=" + this.getCorpTokenByCorpId(corpId) + "&external_userid=" + externalUserid.toString());
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            WechatFollowCustomer wechatFollowCustomer = new WechatFollowCustomer();
            JSONArray followUsers = jsonObject.getJSONArray("follow_user");
            for (Object followUser : followUsers) {
                JSONObject followUserJson = (JSONObject) followUser;
                if (followUserJson.getString("userid").equals(wechatUserid)) {
                    wechatFollowCustomer.setWechatUserId(followUserJson.getString("userid"));
                    wechatFollowCustomer.setRemark(followUserJson.getString("remark"));
                    wechatFollowCustomer.setDescription(followUserJson.getString("description"));
                    wechatFollowCustomer.setWechatCreatetime(followUserJson.getLong("createtime"));
                    wechatFollowCustomer.setWechatRemarkMobiles(followUserJson.getString("remark_mobiles"));
                    JSONArray tags = followUserJson.getJSONArray("tags");
                    List<String> tagIdList = new ArrayList<>();
                    for (Object tag : tags) {
                        JSONObject tagJson = (JSONObject) tag;
                        if (tagJson.getInteger("type") == 1) {
                            tagIdList.add(tagJson.getString("tag_id"));
                        }
                    }
                    wechatFollowCustomer.setWechatTagIds(ObjectUtils.isEmpty(tagIdList) ? null : JSON.toJSONString(tagIdList));
                    wechatFollowCustomer.setRemarkCorpName(followUserJson.getString("remark_corp_name"));
                    wechatFollowCustomer.setAddWay(followUserJson.getInteger("add_way"));
                    wechatFollowCustomer.setOperUserid(followUserJson.getString("oper_userid"));
                    //wechatFollowCustomer.setCustomerNo(followUserJson.getString("remark_corp_name"));
                    break;
                }
            }
            JSONObject externalContact = jsonObject.getJSONObject("external_contact");
            wechatFollowCustomer.setExternalUserid(externalContact.getString("external_userid"));
            wechatFollowCustomer.setWechatName(externalContact.getString("name"));
            wechatFollowCustomer.setWechatType(externalContact.getInteger("type"));
            wechatFollowCustomer.setWechatAuatar(externalContact.getString("avatar"));
            wechatFollowCustomer.setWechatGender(externalContact.getInteger("gender"));
            wechatFollowCustomer.setWechatUnionid(externalContact.getString("unionid"));
            return wechatFollowCustomer;
        }
        return null;
    }

    @Override
    public boolean getUserByUserId(String corpId, String userid) {
        String userPost = OkHttpUtils.X.get(wechatUrl + "/cgi-bin/user/get?access_token=" + this.getCorpTokenByCorpId(corpId)+"&userid="+userid);
        JSONObject jsonObject = JSON.parseObject(userPost);
        if (jsonObject.getInteger("errcode")==0){
           if (!ObjectUtils.isEmpty(jsonObject.getString("userid"))){
               return true;
           }
        }
        return false;
    }

    //获取或更新标签
    private void getAllTags(Long wechatInfoId,String corpid) {
        //获取企业标签
        List<WechatGroupTagVo> wechatGroupTagVoList = getWechatTags(corpid);
        if (!ObjectUtils.isEmpty(wechatGroupTagVoList)) {
            List<WechatTagInfo> wechatTagInfoList = new ArrayList<>();
            for (WechatGroupTagVo wechatGroupTagVo : wechatGroupTagVoList) {
                WechatTagInfo wechatGroupTagInfo = new WechatTagInfo();
                wechatGroupTagInfo.setWechatInfoId(wechatInfoId);
                wechatGroupTagInfo.setWechatGroupId("0");
                wechatGroupTagInfo.setTreePath("0");
                wechatGroupTagInfo.setTagId(wechatGroupTagVo.getGroup_id());
                wechatGroupTagInfo.setLevel(1);
                wechatGroupTagInfo.setTagName(wechatGroupTagVo.getGroup_name());
                wechatGroupTagInfo.setType(1);
                wechatGroupTagInfo.setWechatCreateTime(wechatGroupTagVo.getCreate_time());
                wechatTagInfoList.add(wechatGroupTagInfo);
                List<WechatGroupTagVo.WechatTagVo> tags = wechatGroupTagVo.getTags();
                for (WechatGroupTagVo.WechatTagVo tag : tags) {
                    WechatTagInfo wechatTagInfo = new WechatTagInfo();
                    wechatTagInfo.setWechatInfoId(wechatInfoId);
                    wechatTagInfo.setWechatGroupId(wechatGroupTagInfo.getTagId());
                    wechatTagInfo.setTreePath("0," + wechatGroupTagInfo.getTagId());
                    wechatTagInfo.setTagId(tag.getId());
                    wechatTagInfo.setLevel(2);
                    wechatTagInfo.setTagName(tag.getName());
                    wechatTagInfo.setType(2);
                    wechatTagInfo.setWechatCreateTime(tag.getCreate_time());
                    wechatTagInfo.setWechatOrder(tag.getOrder());
                    wechatTagInfoList.add(wechatTagInfo);
                }
            }
            List<String> tagIdlist = wechatTagInfoList.stream().map(i -> i.getTagId()).toList();
            LambdaQueryWrapper<WechatTagInfo> wechatTagInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            wechatTagInfoLambdaQueryWrapper.select(WechatTagInfo::getId, WechatTagInfo::getTagId)
                    .eq(WechatTagInfo::getWechatInfoId, wechatInfoId)
                    .in(WechatTagInfo::getTagId, tagIdlist);
            List<WechatTagInfo> agoTags = wechatTagInfoService.list(wechatTagInfoLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(agoTags)) {
                List<String> agoTagIds = agoTags.stream().map(i -> i.getTagId()).toList();
                Map<String, Long> collect = agoTags.stream().collect(Collectors.toMap(obj -> obj.getTagId(), obj -> obj.getId()));
                for (WechatTagInfo wechatTagInfo : wechatTagInfoList) {
                    if (agoTagIds.contains(wechatTagInfo.getTagId())) {
                        Long id = collect.get(wechatTagInfo.getTagId());
                        wechatTagInfo.setId(id);
                    }
                }
            }
            wechatTagInfoService.saveOrUpdateBatch(wechatTagInfoList);
        }
    }






    @Override
    public Boolean updateWechatCustomerRemark(String corpId, UpdateWechatCustomerRemarkDto updateWechatCustomerRemarkDto) {
        Map<String, Object> stringObjectMap = BeanCopierUtils.X.convertClassToMap(updateWechatCustomerRemarkDto);
        String post = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/externalcontact/remark?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(stringObjectMap));
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateWechatCustomerTags(String corpId, UpdateWechatCustomerTagsDto updateWechatCustomerTagsDto) {
        Map<String, Object> stringObjectMap = BeanCopierUtils.X.convertClassToMap(updateWechatCustomerTagsDto);
        String post = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/externalcontact/mark_tag?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(stringObjectMap));
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            return true;
        }
        return null;
    }

    @Override
    public LoginDetailVo getuserdetail(String corpId, String user_ticket) {
        Map<String, String> map = new HashMap<>();
        map.put("user_ticket", user_ticket);
        String post = OkHttpUtils.X.post(wechatUrl + "/cgi-bin/auth/getuserdetail?access_token=" + this.getCorpTokenByCorpId(corpId), JacksonUtils.X.format(map));
        JSONObject jsonObject = JSON.parseObject(post);
        if (jsonObject.getString("errmsg").equals("ok")) {
            LoginDetailVo loginDetailVo = new LoginDetailVo();
            loginDetailVo.setUserid(jsonObject.getString("userid"));
            loginDetailVo.setGender(jsonObject.getInteger("gender"));
            loginDetailVo.setAvatar(jsonObject.getString("avatar"));
            loginDetailVo.setQr_code(jsonObject.getString("qr_code"));
            loginDetailVo.setMobile(jsonObject.getString("mobile"));
            loginDetailVo.setEmail(jsonObject.getString("email"));
            loginDetailVo.setBiz_mail(jsonObject.getString("biz_mail"));
            loginDetailVo.setAddress(jsonObject.getString("address"));
            return loginDetailVo;
        }
        return null;
    }


    private static void toWechatInfo(WechatInfo wechatInfo, JSONObject parse) {
        wechatInfo.setPermanentCode(parse.getString("permanent_code"));

        JSONObject authCorpInfo = parse.getJSONObject("auth_corp_info");
        wechatInfo.setCorpid(authCorpInfo.getString("corpid"));
        wechatInfo.setCorpName(authCorpInfo.getString("corp_name"));
        wechatInfo.setCorpType(authCorpInfo.getString("corp_type"));
        wechatInfo.setCorpSquareLogoUrl(authCorpInfo.getString("corp_square_logo_url"));
        wechatInfo.setCorpUserMax(authCorpInfo.getString("corp_user_max"));
        wechatInfo.setCorpFullName(authCorpInfo.getString("corp_full_name"));
        wechatInfo.setSubjectType(authCorpInfo.getString("subject_type"));
        wechatInfo.setVerifiedEndTime(authCorpInfo.getString("verified_end_time"));
        wechatInfo.setCorpWxqrcode(authCorpInfo.getString("corp_wxqrcode"));
        wechatInfo.setCorpScale(authCorpInfo.getString("corp_scale"));
        wechatInfo.setCorpIndustry(authCorpInfo.getString("corp_industry"));
        wechatInfo.setCorpSubIndustry(authCorpInfo.getString("corp_sub_industry"));
        if (!ObjectUtils.isEmpty(parse.getJSONObject("auth_info"))) {
            wechatInfo.setAuthInfo(JSON.toJSONString(parse.getJSONObject("auth_info")));
            JSONObject authInfoJsonObject = JSON.parseObject(parse.getJSONObject("auth_info").toJSONString());
            JSONArray agents = authInfoJsonObject.getJSONArray("agent");
            String agentid = null;
            for (Object agent : agents) {
                JSONObject agentJsonObject = (JSONObject) agent;
                String name = agentJsonObject.getString("name");
                if (name.equals("boker")) {
                    agentid = agentJsonObject.getString("agentid");
                    break;
                }
            }
            wechatInfo.setAgentid(agentid);
        }
        if (!ObjectUtils.isEmpty(parse.getJSONObject("auth_user_info"))) {
            wechatInfo.setAuthUserInfo(JSON.toJSONString(parse.getJSONObject("auth_user_info")));
        }
        if (!ObjectUtils.isEmpty(parse.getJSONObject("register_code_info"))) {
            wechatInfo.setRegisterCodeInfo(JSON.toJSONString(parse.getJSONObject("register_code_info")));
        }
        if (!ObjectUtils.isEmpty(parse.getJSONObject("edition_info"))) {
            wechatInfo.setEditionInfo(JSON.toJSONString(parse.getJSONObject("edition_info")));
        }

        wechatInfo.setCreateTime(new Date());
    }

}
